

const multer = require('koa-multer');
const path = require('path');
const { isExist } = require('../../util/fsIO');

async function multerUploadMiddleware(ctx, next) {
    if (/upload/g.test(ctx.url) && ctx.method === 'POST') {
        const folder = ctx.request.query.folder || 'uploads';
        const storage = multer.diskStorage({
            destination: async function (req, file, cb) {
                const uploadPath = path.resolve(__dirname, `../../public/${folder}`);
                const res = await isExist(uploadPath, true);
                if (!res) {
                    cb(new Error('文件夹创建失败'));
                    return;
                }
                cb(null, path.resolve(__dirname, uploadPath));
            },
            filename: function (req, file, cb) {
                const extname = path.extname(file.originalname)
                const filename = path.basename(file.originalname, extname)
                cb(null, filename + '-' + Date.now() + extname);
            }
        })
        const upload = multer({ storage: storage })
        return upload.single('file')(ctx, next);
    }
    await next();
}




module.exports = multerUploadMiddleware;